import axios, { type Method } from 'axios'
import { getToken, removeToken } from './auth'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import router from '@/router'
const instance = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})
type Data<T> = {
  code: number
  message: string
  data: T
}
export const request = <T>(url: string, method: Method = 'get', submitData?: object) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
instance.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error)
  },
)

instance.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    ElMessage.error(error.response.data.msg);
        // Token 401处理
    // console.dir(error.response.status)
    if (error.response.status === 401) {
      // 1. 跳转到登录
      // const router = useRouter()
      router.push('/login')
      // 2. 清空用户数据
      const store = useUserStore()
      removeToken()
    }
    return Promise.reject(error)
  },
)

export default instance
